﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using HJT212_Protocol_DAL.Model;

namespace HJT212_Protocol_DAL.DAO
{
    public class MsgCacheDao : BaseDao
    {
        /// <summary>
        /// 将第一次发送的请求写入缓存，初次请求由HostClient发起，
        /// 生成QN，此时会把QN与SrvClient的ID的对应缓存起来，
        /// 当本次请求，有回执的时候，以便可知回执给哪个SrvClient
        /// 判断是否是初次请求的操作是根据是根据指令的起始，
        /// 如果以'QN='打头说明是初次请求，
        /// 否则以'ST='打头说明是请求的应答
        /// </summary>
        /// <param name="msgContent">内容</param>
        /// <param name="MN"> </param>
        public void InsertToCache(string msgContent, string MN)
        {
            try
            {
                if (string.IsNullOrEmpty(msgContent.Trim()) || string.IsNullOrEmpty(MN))
                {
                    return;
                }
                string qnd = "QN=";
                //为了较好的兼容性，即便是QN与=间有空格也可取出相应的QN号
                string content = msgContent.ToUpper().Replace(" ", "").Replace("　", "");
                int i = content.IndexOf(qnd);
                //大于0说明是非初次请求，小于0说明是指令信息中无请求码
                string qn = content.Substring(i + 3, 17);
                string insrtSql =
                    @" insert into TB_MESSAGECACHELIST (MN, QN) values ('{0}', '{1}') ";

                string delSql = " delete from TB_MESSAGECACHELIST where QN='{0}' ";

                delSql = string.Format(delSql, qn);
                insrtSql = string.Format(insrtSql, MN, qn);
                helper.ExecuteNonQueryTransaction(new List<string>() { delSql, insrtSql });
                //return qn;
            }
            catch (Exception ex)
            {
                log.Error("出现异常", ex);
            }
        }

        /// <summary>
        /// 根据Qn检索MessageId
        /// </summary>
        /// <param name="Qn"></param>
        /// <returns></returns>
        public string GetMessageIdByQn(string Qn)
        {

            try
            {
                if (string.IsNullOrEmpty(Qn)) return null;
                string sqlSelect = " Select MessageID from TB_MESSAGECACHELIST where QN='{0}' ";
                sqlSelect = string.Format(sqlSelect, Qn);
                var mid = helper.ExecuteScalar(sqlSelect);
                if (mid != null)
                {
                    return mid.ToString();
                }

            }
            catch (Exception ex)
            {
                log.Error("出现异常", ex);
            }
            return null;
        }

        public void InsertToCache(string msgContent, TB_MESSAGECACHELISTModel mdl)
        {
            try
            {
                if (mdl == null || string.IsNullOrEmpty(msgContent.Trim()) || string.IsNullOrEmpty(mdl.MN))
                {
                    return;
                }
                string qnd = "QN=";
                //为了较好的兼容性，即便是QN与=间有空格也可取出相应的QN号
                string content = msgContent.ToUpper().Replace(" ", "").Replace("　", "");
                int i = content.IndexOf(qnd);
                string qn = content.Substring(i + 3, 17);
                string insrtSql =
                    @" insert into TB_MESSAGECACHELIST (MN, QN,MessageID) values ('{0}', '{1}','{2}') ";
                insrtSql = string.Format(insrtSql, mdl.MN, qn, mdl.MessageID);
                string delSql = " delete from TB_MESSAGECACHELIST where QN='{0}' ";
                delSql = string.Format(delSql, qn);
                helper.ExecuteNonQueryTransaction(new List<string>() { delSql, insrtSql });
                //return qn;
            }
            catch (Exception ex)
            {
                log.Error("出现异常", ex);
            }
        }

        /// <summary>
        /// 从缓存中根据QN检索相应的MN，从而定位到相应的上位机
        /// </summary>
        /// <returns></returns>
        public string FindMNByQNFromCache(string QN)
        {
            try
            {
                if (string.IsNullOrEmpty(QN))
                {
                    return null;
                }
                string sqlSelect = " select top 1 MN, QN from TB_MESSAGECACHELIST where  QN='{0}' ";
                sqlSelect = string.Format(sqlSelect, QN);
                DataTable dt = helper.Data_Table(sqlSelect);
                if (dt != null && dt.Rows.Count > 0)
                {
                    string MN = string.Format("{0}", dt.Rows[0]["MN"]);
                    return MN;
                }
            }
            catch (Exception ex)
            {
                log.Error("出现异常", ex);
            }
            return null;
        }


        /// <summary>
        /// 缓存定时清理
        /// </summary>
        /// <param name="lstSql">清理的Sql</param>
        public void ClearCache()
        {
            try
            {
                string strSQlDelSend = "delete from CMD_Send where RecordTime<'{0}' ";
                string strSQlDelReturn = "delete from CMD_Send where RecordTime<'{0}' ";
                string strSQlDelMESSAGECACHE = "delete from TB_MESSAGECACHELIST where SENDTIME<'{0}' ";
                string Dt = DateTime.Now.AddDays(-2).ToString();
                strSQlDelSend = string.Format(strSQlDelSend, Dt);
                strSQlDelReturn = string.Format(strSQlDelReturn, Dt);
                strSQlDelMESSAGECACHE = string.Format(strSQlDelMESSAGECACHE, Dt);
                List<string> lstSql = new List<string>() { strSQlDelSend, strSQlDelReturn, strSQlDelMESSAGECACHE };
                helper.ExecuteNonQueryTransaction(lstSql);
            }
            catch (Exception ex)
            {
                log.Error("出现异常", ex);
            }
        }


    }
}
